/**
 * @file date-range
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {findDOMNode} from 'react-dom';
import * as cx from 'classnames';
import './rich-text.scss';
import * as Editor from './react-codemirror';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/jsx/jsx';
import 'codemirror/mode/css/css';
import 'codemirror/addon/fold/foldgutter';
import 'codemirror/addon/fold/brace-fold';
import 'codemirror/addon/search/search';
import 'codemirror/addon/search/searchcursor';
import 'codemirror/addon/search/jump-to-line';

export default class CodeMirrorEditor extends PureComponent
{
  static propTypes = {
    className: PropTypes.string,
    onChange: PropTypes.func.isRequired
  };

  static defaultProps = {
    onChange: value => console.log(value),
    className: 'form-control code-mirror-editor-control ',
    width: '100%',
    height: '200px',
    mode: 'json'
  };

  constructor(props) {
    super(props);

    this.state = {
      focused: false
    };

    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  handleFocus() {
    this.setState({
      focused: true
    });
  }

  handleBlur() {
    this.setState({
      focused: false
    });
  }


  render() {
    const {
      className,
      ideClassName,
      onChange,
      value,
      mode,
      editorOnly,
      disabled
    } = this.props;
    const focused = this.state.focused;

    const options = {
      lineNumbers: true,
      tabSize: 2,
      indentUnit: 2,
      indentWithTabs: true,
      foldGutter: true,
      smartIndent: false,
      electricChars: false,
      mode: mode === 'json' ? {mode: 'javascript', json: true} : mode,
      matchBrackets: true,
      readOnly: disabled
    };

    let body = (
      <Editor
        className={ideClassName}
        onChange={onChange}
        value={value}
        options={options}
        onFocusChange={focused => focused ? this.handleFocus() : this.handleBlur()}
      />
    );

    if (editorOnly) {
      return body;
    }

    return (
      <div className={cx('code-mirror-editor-control', className, {
        focus: focused
      })}>
        {body}
      </div>
    );
  }
}
